package com.luculent.action;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.luculent.base.section.FPJRSend;
import com.luculent.result.Response;
import com.luculent.utils.EncryptUtils;
import com.luculent.utils.FPJRTableUtils;

import lombok.extern.slf4j.Slf4j;


@Controller 
@RequestMapping("/cf_fpjr/neimenggulangkunfupin")
@Slf4j
public class FPJRController extends FPJRSend{
	
	private static final Logger logger = LoggerFactory.getLogger(FPJRController.class);
    
	private static String agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36";
	 
	
	@RequestMapping(params ="iw-cmd=login") 
	@ResponseBody
    public String login(HttpSession session,@RequestParam(value="username",required = true) String username,
    		@RequestParam(value="password",required = true) String password) throws UnsupportedOperationException, IOException{
		Response response = new Response();
		response.head.rtnCode = "000000"; 
		HttpClient client =  getClient(); 
		HttpPost siginPost = new HttpPost("http://localhost/cpad_coop/login"); 
		siginPost.setHeader("User-Agent", agent); 
		siginPost.setHeader("Content-Type", "application/x-www-form-urlencoded"); 
		List<NameValuePair> list = new ArrayList<NameValuePair>();  
		list.add(new BasicNameValuePair("account",username));
		list.add(new BasicNameValuePair("pwd",password));
		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,"UTF-8");
		siginPost.setEntity(entity); 
		HttpResponse HtmlResp = client.execute(siginPost); 
		if(HtmlResp.getEntity() != null){
			String jsonStr = EntityUtils.toString(HtmlResp.getEntity(), Charset.forName("UTF-8"));
			JsonParser jp=new JsonParser(); 
			String sr = "";
			try {
				if(StringUtils.isBlank(jsonStr)){
					response.head.rtnCode = "999999";
					response.head.rtnMsg = "请求异常";
					return response.toJson();
				}
				
				Document doc = Jsoup.parse(jsonStr); 
				
				Elements scripts = doc.select("script");
				boolean findIt = false;
				for(Element script : scripts){
					//注意这里一定是html(), 而不是text()
					
				   if(script.html().contains("var rs = ")){  
					   findIt = true;
					   String str = script.html().replace("\n", ""); //这里是为了解决 无法多行匹配的问题 
					   sr = str.substring(str.indexOf("var rs = ")+10,str.indexOf("}}'")+2); 
					   JsonObject jo=jp.parse(sr).getAsJsonObject();   
					   
					   if(jo.get("header").getAsJsonObject().get("code").getAsInt()!=1){
						   response.head.rtnCode = "900002";
						   response.head.rtnMsg = "用户名或密码错误";
						   return response.toJson();
					   }else if(jo.get("header").getAsJsonObject().get("code").getAsInt()==1){
						   token =  jo.get("body").getAsJsonObject().get("parameters").getAsJsonObject().get("AccessToken").getAsJsonObject().get("token").getAsString();
						   account =  jo.get("body").getAsJsonObject().get("parameters").getAsJsonObject().get("AccessToken").getAsJsonObject().get("account").getAsString();
						   response.head.rtnCode = "000000";
						   response.head.rtnMsg = "请求成功";
						   return response.toJson();
					   }else{
							response.head.rtnCode = "900006";
							response.head.rtnMsg = jo.get("header").getAsJsonObject().get("message").getAsJsonObject().get("detail").getAsString();
							return response.toJson();
					   } 
				   }
				     
				} 
				if(!findIt){
					response.head.rtnCode = "900002";
					response.head.rtnMsg = "用户名或密码错误";
				}
			} catch (Exception e) {
				response.head.rtnMsg = sr;
				logger.error("登录出现错误",e);
			}
	    }else{
	    	response.head.rtnCode = "999999"; 
	    	response.head.rtnMsg = "系统返回异常"; 
	    }  
		return response.toJson();
    } 
	
	@RequestMapping(params ="iw-cmd=daikunxinxi") 
	@ResponseBody
    public String daikunxinxi(@RequestParam(value="YM",required = false) String ym,
    		@RequestParam(value="XIAN",required = false) String xian,
    		@RequestParam(value="BEGINTIME",required = false) String beginTime,
    		@RequestParam(value="ENDTIME",required = false) String endTime) throws ClientProtocolException, IOException{
		Response response = new Response();
		response.head.rtnCode = "000000"; 
		if(super.account == null || super.token == null){
			response.head.rtnCode = "900001"; 
	    	response.head.rtnMsg = "未登录或登录超时";
	    	return response.toJson();
		} 
		
		if(StringUtils.isBlank(xian)||StringUtils.isBlank(beginTime) || StringUtils.isBlank(endTime)){
			response.head.rtnCode = "900004"; 
	    	response.head.rtnMsg = "未输入参数或参数格式有误";
	    	return response.toJson();
		}
		String pageSize = "30";
		if(StringUtils.isBlank(ym)){
			ym = "1";
		} 
        
        //拼接查询参数 
        String condition = "{\"body\":{\"parameters\":{},\"opt\":\"query\",\"dataStores\":{\"result\":{\"name\":\"result\",\"rowSetName\":\"\",\"rowSet\":{\"primary\":[],\"delete\":[],\"filter\":[]},\"recordCount\":612,\"condition\":{\"sys_menu_id\":\"\",\"CITY_ID\":\"150400000000\",\"districtall\":\"case '$where2'when '10' then(SELECT AAR009 FROM AA11 WHERE AAR001=(substr(Db01.aar008,0,2)||'0000000000'))when '20' then(SELECT AAR009 FROM AA11 WHERE AAR001=(substr(Db01.aar008,0,4)||'00000000'))when '40' then(SELECT AAR009 FROM AA11 WHERE AAR001=(substr(Db01.aar008,0,6)||'000000'))when '50' then(SELECT AAR009 FROM AA11 WHERE AAR001=(substr(Db01.aar008,0,9)||'000'))when '60' then(SELECT AAR009 FROM AA11 WHERE AAR001= Db01.aar008 )end\",\"checks\":\""+beginTime+"\",\"PROVINCE_ID\":\"150000000000\",\"operateOrg\":\"150400000000\",\"sys_operate_Type\":\"02\",\"operateOrgLevel\":\"40\",\"COUNTY\":\""+xian.substring(0,6)+"\",\"distlevel\":\"50\",\"PROVINCE\":\"15\",\"COUNTY_ID\":\""+xian+"\",\"sys_operate_User\":\""+account+"\",\"CITY\":\"1504\",\"sys_operate_key_Info\":\"query_cha\",\"checke\":\""+endTime+"\"},\"sqlProperties\":{\"sqlID\":100000000051214,\"queryID\":\"query_cha\"},\"pageSize\":"+pageSize+",\"pageNumber\":"+ym+",\"parameters\":{},\"pk\":{}}}},\"header\":{},\"bsid\":null}";
        try{
	        //加密处理
	        String nowTime = System.currentTimeMillis()+"";   
	        String content  = EncryptUtils.sha256_HMAC("post:"+method+":"+condition+":"+nowTime,token);
	        HttpClient client =  getClient(); 
	        HttpPost httpPost = getPost(nowTime,account,content,condition); 
	        HttpResponse rResponse = client.execute(httpPost); 
	        
	        //处理返回请求
	        HttpEntity result = rResponse.getEntity();
	        String jsonStr = EntityUtils.toString(result, "UTF-8");
	        JsonParser jp=new JsonParser(); 
	        JsonObject jo=jp.parse(jsonStr).getAsJsonObject();
	        JsonArray data = jo.get("body").getAsJsonObject().get("dataStores").getAsJsonObject().get("result").getAsJsonObject().get("rowSet").getAsJsonObject().get("primary").getAsJsonArray();
	        if(data == null || data.size() == 0){
	        	response.head.rtnCode = "900005"; 
				response.head.rtnMsg = "没有当前查询信息";
				return response.toJson();
	        }
	        if(data.size() == 1){
	        	Gson gson = new Gson(); 
	        	List<Map<String,String>> dataList = gson.fromJson(data, new TypeToken<List<Map<String,String>>>() {}.getType());  
	        	if("合计".equals(dataList.get(0).get("AAR009"))){
	        		response.head.rtnCode = "900005"; 
					response.head.rtnMsg = "没有当前查询信息";
					return response.toJson();	
	        	} 
	        }
	        //进行sql转换 
	        response.body.sql = FPJRTableUtils.daikunxinxi(data, xian, beginTime, endTime);
	        response.body.size = pageSize;
	        response.body.totalCount = jo.get("body").getAsJsonObject().get("dataStores").getAsJsonObject().get("result").getAsJsonObject().get("recordCount").getAsString();
	        response.head.rtnMsg = "请求成功";
	        log.debug(response.body.sql);
		} catch (Exception e) {
			response.head.rtnCode = "999999"; 
			response.head.rtnMsg = "请求发生异常";
			e.printStackTrace();
			logger.debug(e.getMessage());
		} 
        return response.toJson();
    } 
	
	
	@RequestMapping(params ="iw-cmd=huankunxinxi") 
	@ResponseBody
    public String huankunxinxi(@RequestParam(value="YM",required = false) String ym,
    		@RequestParam(value="XIAN",required = false) String xian,
    		@RequestParam(value="BEGINTIME",required = false) String beginTime,
    		@RequestParam(value="ENDTIME",required = false) String endTime) throws IOException{
		Response response = new Response();
		response.head.rtnCode = "000000"; 
		if(super.account == null || super.token == null){
			response.head.rtnCode = "900001"; 
	    	response.head.rtnMsg = "未登录或登录超时";
	    	return response.toJson();
		} 
		
		if(StringUtils.isBlank(xian)||StringUtils.isBlank(beginTime) || StringUtils.isBlank(endTime)){
			response.head.rtnCode = "900004"; 
	    	response.head.rtnMsg = "未输入参数或参数格式有误";
	    	return response.toJson();
		}
		String pageSize = "30";
		if(StringUtils.isBlank(ym)){
			ym = "1";
		} 
        
        //拼接查询参数 
		String condition ="{\"body\":{\"parameters\":{},\"opt\":\"query\",\"dataStores\":{\"result\":{\"name\":\"result\",\"rowSetName\":\"\",\"rowSet\":{\"primary\":[],\"delete\":[],\"filter\":[]},\"recordCount\":612,\"condition\":{\"sys_menu_id\":\"\",\"CITY_ID\":\"150400000000\",\"districtall\":\"case '$where2'when '10' then(SELECT AAR009 FROM AA11 WHERE AAR001=(substr(Db04.aar008,0,2)||'0000000000'))when '20' then(SELECT AAR009 FROM AA11 WHERE AAR001=(substr(Db04.aar008,0,4)||'00000000'))when '40' then(SELECT AAR009 FROM AA11 WHERE AAR001=(substr(Db04.aar008,0,6)||'000000'))when '50' then(SELECT AAR009 FROM AA11 WHERE AAR001=(substr(Db04.aar008,0,9)||'000'))when '60' then(SELECT AAR009 FROM AA11 WHERE AAR001= Db04.aar008 )end\",\"checks\":\""+beginTime+"\",\"PROVINCE_ID\":\"150000000000\",\"operateOrg\":\"150400000000\",\"sys_operate_Type\":\"02\",\"operateOrgLevel\":\"40\",\"COUNTY\":\""+xian.substring(0,6)+"\",\"distlevel\":\"50\",\"PROVINCE\":\"15\",\"COUNTY_ID\":\""+xian+"\",\"sys_operate_User\":\""+account+"\",\"CITY\":\"1504\",\"sys_operate_key_Info\":\"query_cha\",\"checke\":\""+endTime+"\"},\"sqlProperties\":{\"sqlID\":201707121410,\"queryID\":\"query_repayManagement\"},\"pageSize\":"+pageSize+",\"pageNumber\":"+ym+",\"parameters\":{},\"pk\":{}}}},\"header\":{},\"bsid\":null}";
	    try{
	        //加密处理
	        String nowTime = System.currentTimeMillis()+"";   
	        String content  = EncryptUtils.sha256_HMAC("post:"+method+":"+condition+":"+nowTime,token);
	        HttpClient client =  getClient(); 
	        HttpPost httpPost = getPost(nowTime,account,content,condition); 
	        HttpResponse rResponse = client.execute(httpPost); 
	        
	        //处理返回请求
	        HttpEntity result = rResponse.getEntity();
	        String jsonStr = EntityUtils.toString(result, "UTF-8");
	        JsonParser jp=new JsonParser(); 
	        JsonObject jo=jp.parse(jsonStr).getAsJsonObject();
	        JsonArray data = jo.get("body").getAsJsonObject().get("dataStores").getAsJsonObject().get("result").getAsJsonObject().get("rowSet").getAsJsonObject().get("primary").getAsJsonArray();
	        if(data == null || data.size() == 0){
	        	response.head.rtnCode = "900005"; 
				response.head.rtnMsg = "没有当前查询信息";
				return response.toJson();
	        }
	        if(data.size() == 1){
	        	Gson gson = new Gson(); 
	        	List<Map<String,String>> dataList = gson.fromJson(data, new TypeToken<List<Map<String,String>>>() {}.getType());  
	        	if("合计".equals(dataList.get(0).get("AAR009"))){
	        		response.head.rtnCode = "900005"; 
					response.head.rtnMsg = "没有当前查询信息";
					return response.toJson();	
	        	} 
	        }
	        //进行sql转换 
	        response.body.sql = FPJRTableUtils.daikunxinxi(data, xian, beginTime, endTime);
	        response.body.size = pageSize;
	        response.body.totalCount = jo.get("body").getAsJsonObject().get("dataStores").getAsJsonObject().get("result").getAsJsonObject().get("recordCount").getAsString();
	        response.head.rtnMsg = "请求成功";
	        log.debug(response.body.sql);
		} catch (Exception e) {
			response.head.rtnCode = "999999"; 
			response.head.rtnMsg = "请求发生异常";
			e.printStackTrace();
			logger.debug(e.getMessage());
		} 
        return response.toJson();
    } 
	@RequestMapping(params ="iw-cmd=yuqixinxi") 
	@ResponseBody
    public String yuqixinxi(@RequestParam(value="YM",required = false) String ym,
    		@RequestParam(value="XIAN",required = false) String xian,
    		@RequestParam(value="BEGINTIME",required = false) String beginTime,
    		@RequestParam(value="ENDTIME",required = false) String endTime) throws IOException{
		Response response = new Response();
		response.head.rtnCode = "000000"; 
		if(super.account == null || super.token == null){
			response.head.rtnCode = "900001"; 
	    	response.head.rtnMsg = "未登录或登录超时";
	    	return response.toJson();
		} 
		
		if(StringUtils.isBlank(xian)||StringUtils.isBlank(beginTime) || StringUtils.isBlank(endTime)){
			response.head.rtnCode = "900004"; 
	    	response.head.rtnMsg = "未输入参数或参数格式有误";
	    	return response.toJson();
		}
		String pageSize = "30";
		if(StringUtils.isBlank(ym)){
			ym = "1";
		} 
        
        //拼接查询参数 
		String condition ="{\"body\":{\"parameters\":{},\"opt\":\"query\",\"dataStores\":{\"result\":{\"name\":\"result\",\"rowSetName\":\"\",\"rowSet\":{\"primary\":[],\"delete\":[],\"filter\":[]},\"recordCount\":25,\"condition\":{\"sys_menu_id\":\"\",\"CITY_ID\":\"150400000000\",\"districtall\":\"case '$where2'when '10' then(SELECT AAR009 FROM AA11 WHERE AAR001=(substr(Db06.aar008,0,2)||'0000000000'))when '20' then(SELECT AAR009 FROM AA11 WHERE AAR001=(substr(Db06.aar008,0,4)||'00000000'))when '40' then(SELECT AAR009 FROM AA11 WHERE AAR001=(substr(Db06.aar008,0,6)||'000000'))when '50' then(SELECT AAR009 FROM AA11 WHERE AAR001=(substr(Db06.aar008,0,9)||'000'))when '60' then(SELECT AAR009 FROM AA11 WHERE AAR001= Db06.aar008 )end\",\"checks\":\""+beginTime+"\",\"PROVINCE_ID\":\"150000000000\",\"operateOrg\":\"150400000000\",\"sys_operate_Type\":\"02\",\"operateOrgLevel\":\"40\",\"COUNTY\":\""+xian.substring(0,6)+"\",\"distlevel\":\"50\",\"PROVINCE\":\"15\",\"COUNTY_ID\":\"150421000000\",\"sys_operate_User\":\"150401\",\"CITY\":\"1504\",\"sys_operate_key_Info\":\"query_overdueManagement\",\"checke\":\""+endTime+"\"},\"pageSize\":"+pageSize+",\"sqlProperties\":{\"sqlID\":201707121411,\"queryID\":\"query_overdueManagement\"},\"pageNumber\":"+ym+",\"parameters\":{},\"pk\":{}}}},\"header\":{},\"bsid\":null}";
		try{
	        //加密处理
	        String nowTime = System.currentTimeMillis()+"";   
	        String content  = EncryptUtils.sha256_HMAC("post:"+method+":"+condition+":"+nowTime,token);
	        HttpClient client =  getClient(); 
	        HttpPost httpPost = getPost(nowTime,account,content,condition); 
	        HttpResponse rResponse = client.execute(httpPost); 
	        
	        //处理返回请求
	        HttpEntity result = rResponse.getEntity();
	        String jsonStr = EntityUtils.toString(result, "UTF-8");
	        JsonParser jp=new JsonParser(); 
	        JsonObject jo=jp.parse(jsonStr).getAsJsonObject();
	        JsonArray data = jo.get("body").getAsJsonObject().get("dataStores").getAsJsonObject().get("result").getAsJsonObject().get("rowSet").getAsJsonObject().get("primary").getAsJsonArray();
	        if(data == null || data.size() == 0){
	        	response.head.rtnCode = "900005"; 
				response.head.rtnMsg = "没有当前查询信息";
				return response.toJson();
	        }
	        if(data.size() == 1){
	        	Gson gson = new Gson(); 
	        	List<Map<String,String>> dataList = gson.fromJson(data, new TypeToken<List<Map<String,String>>>() {}.getType());  
	        	if("合计".equals(dataList.get(0).get("AAR009"))){
	        		response.head.rtnCode = "900005"; 
					response.head.rtnMsg = "没有当前查询信息";
					return response.toJson();	
	        	} 
	        }
	        //进行sql转换 
	        response.body.sql = FPJRTableUtils.yuqixinxi(data, xian, beginTime, endTime);
	        response.body.size = pageSize;
	        response.body.totalCount = jo.get("body").getAsJsonObject().get("dataStores").getAsJsonObject().get("result").getAsJsonObject().get("recordCount").getAsString();
	        response.head.rtnMsg = "请求成功";
	        log.debug(response.body.sql);
		} catch (Exception e) {
			response.head.rtnCode = "999999"; 
			response.head.rtnMsg = "请求发生异常";
			e.printStackTrace();
			logger.debug(e.getMessage());
		} 
        return response.toJson();
    } 
}